<?php

class News extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'News':
	 * @var integer $id
	 * @var string $title
	 * @var string $context
	 * @var string $pic1
	 * @var string $pic2
	 * @var integer $state
	 * @var string $create_time
	 */
	
	private $_kind=array(1=>'行业信息',2=>'专业知识',3=>'北京家具城导航',4=>'企业名录',5=>'政策法规',6=>'软文');
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'news';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('title','length','max'=>50),
			array('pic1','length','max'=>100),
			array('pic2','length','max'=>100),
			array('title,context,kind', 'required'),
		);
	}
	
	/**
	 * Prepares attributes before performing validation.
	 */
	protected function beforeValidate($on)//在验证之前将无需用户输入的字段写入
	{
		if($this->isNewRecord){
			$this->state=0;
			$this->create_time=date('Y-m-d G:i:s');
		}
		return true;
	}
	
	protected function afterValidate($on){
		if($this->hasErrors()) return;
		$this->pic1='';$this->pic2='';
		$basePath=Yii::app()->basePath.'/../';
 		preg_match_all('/\ssrc=\"([^\"]*)\"/iUs',$this->context,$match);
 		foreach($match[1] as $key=>$val){
 			if($key>1) break;
 			$path=preg_replace('/temp\//','',$val);
 			$pic_name='pic'.($key+1);
 			$this->$pic_name=$path;
 			@mkdir(dirname($basePath.$path), 0777,true);
			@fclose(fopen(dirname($basePath.$path).'/index.htm', 'w'));
			@rename($basePath.$val,$basePath.$path);
 		}
 		$this->context=preg_replace('/upload\/temp\/news\//','upload/news/',$this->context);
	}
	
	public function getKindNames(){
		return $this->_kind;
	}
	
	public function getKindName($n=null){
		return $n==null?$this->_kind[$this->kind]:$this->_kind[$n];
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => '索引',
			'title' => '标题',
			'kind' => '文档类型',
			'context' => '内容',
			'pic1' => '图片1路径',
			'pic2' => '图片2路径',
			'state' => '状态',
			'create_time' => '创建时间',
		);
	}
}